<template>
    <div>
        <h3>
            <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointe blue bigger-110"></i>&nbsp;
            <router-link to="/business/course" class="blue">发布新产品<!--{{course.name}}--></router-link>
        </h3>
        <hr>

        <big-file-icon v-bind:file-id="'course-content-file-upload'"
                       v-bind:text="'上传文件'"
                       v-bind:suffix-tag="['jpg','jpeg','png','gif','mp4','avi','mov','3gp','wmv']"
                       v-bind:use="FILE_USE.COURSE.key"
                       v-bind:after-upload="afterUploadCourseContentFile"
        ></big-file-icon>
        <br>
        <table id="course-content-file-table" class="table table-bordered table-hover">
            <thead>
            <tr>
                <th>文件名称</th>
                <th>文件地址</th>
                <th>文件大小</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(file) in files" :key="file.id.index">
                <td>{{file.name}}</td>
                <td>{{file.url}}</td>
                <td>{{file.size | formatFileSize}}</td>

                <td>
                    <button class="btn btn-xs btn-danger" v-on:click="delFile(file)">
                        <i class="ace-icon fa fa-trash-o bigger-120"></i>删除
                    </button>
                </td>
            </tr>
            </tbody>
        </table>

        <form class="form-horizontal">
            <div class="form-group">
                <div class="col-lg-12">
                    <!--显示最后保存的时间-->
                    {{saveContentLabel}}
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-12" for="form-field-1"> 产品名称: </label>

                <div class="col-lg-12">
                    <input type="text" id="form-field-1" placeholder="请输入独立信息标题" class="col-xs-10 col-sm-5"/>
                </div>
            </div>

            <div class="form-group">
                <label class="col-lg-12 " for="form-field-2"> 产品标题: </label>

                <div class="col-lg-12">
                    <input type="text" id="form-field-2" placeholder="标签不能是中文，例如：About" class="col-xs-10 col-sm-5"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-12 " for="form-field-3"> 关键字: </label>

                <div class="col-lg-12">
                    <input type="text" id="form-field-3" placeholder="SEO关键字，用英文逗号隔开" class="col-xs-10 col-sm-5"/>
                </div>
            </div>

            <div class="form-group">
                <label class="col-lg-12 " for="form-field-8">产品描述</label>
                <div class="col-lg-6">
                    <el-input id="form-field-8" type="textarea" :autosize="{minRows:5,maxRows:5}"
                              placeholder="填写SEO描述"></el-input>
                </div>
            </div>

            <div class="form-group">
                <label class="col-lg-12 " style="display:block;float:left"> 产品题图: </label>
                <el-upload style="float:left;margin-left:10px;"
                           class="upload-demo"
                           action="https://jsonplaceholder.typicode.com/posts/"
                           :on-preview="handlePreview"
                           :on-remove="handleRemove"
                           :file-list="fileList"
                           list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </div>

            <!--<div class="form-group">
                <label class="col-lg-12 " > 文章题图: </label>
                <MultiUpload class="col-lg-12" v-model="spu.decript"></MultiUpload>
                &lt;!&ndash;<div class="col-lg-12">
                    <input type="text" id="form-field-4" placeholder="标签不能是中文，例如：About" class="col-xs-10 col-sm-5" />
                </div>&ndash;&gt;
            </div>-->

            <div class="form-group">
                <label class="col-lg-12 " for="form-field-5"> 标签: </label>

                <div class="col-lg-12">
                    <input type="text" id="form-field-5" placeholder="标签不能是中文，例如：About" class="col-xs-10 col-sm-5"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-12 "> 是否显示 </label>
                <el-switch prop="valueType" class="col-lg-6"
                           v-model="dataForm.valueType"
                           active-text="开"
                           inactive-text="关"
                           active-color="#13ce66"
                           inactive-color="#ff4949"
                           :inactive-value="0"
                           :active-value="1"
                ></el-switch>
            </div>

            <div class="form-group">
                <div class="col-lg-12">
                    <!--富文本框位置-->
                    <div id="courseContent"></div>
                </div>
            </div>
        </form>
        <p>
            <button type="button" class="btn btn-bold btn-success btn-round " v-on:click="saveCourseContent()">
                <i class="ace-icon fa fa-save bigger-110"></i>
                保存
            </button>&nbsp;&nbsp;
            <router-link to="/business/course" type="button" class="btn btn-bold btn-success btn-round "
                         data-dismiss="modal">
                <i class="ace-icon fa fa-backward bigger-110"></i>
                返回课程
            </router-link>
        </p>
    </div>
</template>

<script>
    //import FileIcon from "../../components/file-icon";
    import BigFileIcon from "../../components/big-file-icon";

    export default {
        name: "product-content",
        //components: {BigFileIcon, FileIcon},MultiUpload,
        components: {BigFileIcon},
        data: function () {
            return {
                course: {},
                FILE_USE: FILE_USE,
                saveContentLabel: "",
                //原来是打开模态框，开启定时保存，关闭模态框，清除定时任务。
                // 现改为mounted初始化时，开启，页面组件销毁时destroyed，清除定时器
                saveContentIntervalLabel: {},
                files: [],
                dataForm: {
                    attrId: 0,
                    attrName: "",
                    searchType: 0,
                    valueType: 1,
                    icon: "",
                    valueSelect: "",
                    attrType: 1,
                    enable: 1,
                    catelogId: "",
                    attrGroupId: "",
                    showDesc: 0
                },
                fileList: [{
                    name: 'food.jpeg',
                    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
                }, {
                    name: 'food2.jpeg',
                    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
                }],
            }
        },
        mounted: function () {
            let _this = this;
            let course = SessionStorage.get(SESSION_KEY_COURSE) || {};
            if (Tool.isEmpty(course)) {
                _this.$router.push("/welcome");
            }
            _this.course = course;
            _this.initContent();
            this.$parent.activeSidebar("business-course-sidebar");
        },
        destroyed: function () {
            let _this = this;
            console.log("销毁组件");
            clearInterval(_this.saveContentIntervalLabel);
        },
        methods: {
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            /**
             * 编辑内容按钮：打开编辑框
             */
            initContent() {
                let _this = this;
                let course = _this.course;
                let id = course.id;
                _this.course = course;
                $("#courseContent").summernote({
                    focus: true,
                    height: 300
                });
                //先清空历史内容
                $("#courseContent").summernote('code', '');
                //再清空interval自动保存的时间
                _this.saveContentLabel = "";
                //加载文件列表
                _this.listCourseContentFiles();
                Loading.show();
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/business/admin/course/find-course-content/' + id)
                    .then((responseDto) => {
                        Loading.hide();
                        let response = responseDto.data;
                        if (response.success) {
                            //保存成功不关闭内容框，这里跳转新页面，无需启动不关闭
                            //$("#course-content-modal").modal({backdrop:'static',keyboard:false});
                            if (response.responseData) {
                                //写入内容库
                                $("#courseContent").summernote('code', response.responseData.content);
                            }
                            //开启定时自动保存5s
                            _this.saveContentIntervalLabel = setInterval(function () {
                                _this.saveCourseContent();
                            }, 5000);
                        } else {
                            Toast.warning(response.responseMsg);
                        }
                    });
            },
            /**
             * 插入课程内容
             */
            saveCourseContent() {
                let _this = this;
                //读取文本框代码
                let content = $("#courseContent").summernote("code");
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/save-course-content',
                    {
                        id: _this.course.id,
                        content: content
                    })
                    .then((response) => {
                        Loading.hide();
                        let resp = response.data;
                        if (resp.success) {
                            let now = Tool.dateFormat("yyyy-MM-dd hh:mm:ss");
                            _this.saveContentLabel = "[ 最后保存时间：] " + now;
                            //Toast.success("课程内容保存成功！");
                        } else {
                            Toast.warning(resp.responseMsg);
                        }
                    });
            },

            /**
             * 加载文件列表
             */
            listCourseContentFiles() {
                let _this = this;
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/business/admin/course-content-file/list/'
                    + this.course.id)
                    .then((responseFiles) => {
                        let response = responseFiles.data;
                        if (response.success) {
                            //
                            _this.files = response.responseData;
                        }
                    })
            },
            /**
             * 上传文件内容后，保存文件记录
             * 1.使用文件上传组件file-icon上传文件，保存file表记录
             * 2.这里获取到上传结果，启动controller做course-content-file插入
             */
            afterUploadCourseContentFile(responseSaveFile) {
                let _this = this;
                console.log("开始保存文件");
                //
                let file = responseSaveFile.responseData;
                file.courseId = _this.course.id;
                file.url = file.path;
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course-content-file/save', file)
                    .then((responseSave) => {
                        let response = responseSave.data;
                        if (response.success) {
                            Toast.success("文件上传成功！");
                            //没有push进去，但数据库有了，刷新页面出现
                            //_this.files.push(response.responseData);
                            _this.listCourseContentFiles();
                        }
                    });
            },
            //这里的删除，只删除course-content-file表数据，不删除file表数据，会导致脏数据
            delFile(file) {
                let _this = this;
                Confirm.show("删除课程后不可恢复，确认删除？", function () {
                    _this.$ajax.delete(process.env.VUE_APP_SERVER + '/business/admin/course-content-file/delete/' + file.id)
                        .then((responseDelFile) => {
                            let response = responseDelFile.data;
                            if (response.success) {
                                Toast.success("删除文件成功！");
                                //采用前端删除，不调用list方法
                                Tool.removeObj(_this.files, file);
                            }
                        })
                })
            }
        }
    }
</script>

<style scoped>

</style>